package com.agileai.portal.portlets.wcmlist;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.PortletPreferences;
import javax.portlet.ProcessAction;
import javax.portlet.ReadOnlyException;
import javax.portlet.RenderMode;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ValidatorException;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.domain.DataRow;
import com.agileai.hotweb.common.StringTemplateLoader;
import com.agileai.portal.bizmoduler.wcm.InfomationManage;
import com.agileai.portal.driver.GenericPotboyPortlet;
import com.agileai.portal.driver.common.PreferenceException;
import com.agileai.portal.driver.common.PreferencesHelper;
import com.agileai.portal.driver.common.PreferencesWrapper;
import com.agileai.portal.portlets.PortletCacheManager;
import com.agileai.util.StringUtil;

import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;

public class InfomationListEx extends GenericPotboyPortlet {
	@RenderMode(name = "view")
	public void view(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PortletPreferences preferences =  PreferencesHelper.getPublicPreference(request);
		String templateId = preferences.getValue("templateId", null);
		String columnId = preferences.getValue("columnId", null);
		String unShowColumnIds = preferences.getValue("unShowColumnIds", null);
		String maxCount = preferences.getValue("maxCount", null);
		String sortPolicy = preferences.getValue("sortPolicy", null);
		String infoLinkURL = preferences.getValue("infoLinkURL", null);
		String moreLinkURL = preferences.getValue("moreLinkURL", null);
		
		if (!StringUtil.isNullOrEmpty(templateId) 
				&& !StringUtil.isNullOrEmpty(maxCount)
				&& !StringUtil.isNullOrEmpty(sortPolicy) && !StringUtil.isNullOrEmpty(infoLinkURL) 
				){
			request.setAttribute("isSetting", "Y");
		}else{
			request.setAttribute("isSetting", "N");
		}
		
		String isSetting = (String)request.getAttribute("isSetting");
		if ("Y".equals(isSetting)){
			String sessionId = request.getPortletSession().getId();
			String urlPrefix = PortletCacheManager.buildDataURLPefix(request);
			String dataURL = urlPrefix+"/resource;jsessionid="+sessionId+"?ContentProvider&actionType=findInfomationListEx&columnId="+columnId+"&unShowColumnIds="+unShowColumnIds+"&maxCount="+maxCount+"&sortPolicy="+sortPolicy;
			try {
				String jsonData = this.retrieveData(preferences, dataURL);
				InfomationsModel infoListModel = new InfomationsModel();
				infoListModel.setColumnId(columnId);
				JSONObject jsonObject = new JSONObject(jsonData);
				if (StringUtil.isNotNullNotEmpty(columnId)){
					infoListModel.setColumnName(jsonObject.getString("columnName"));
					infoListModel.setColumnTitle(jsonObject.getString("columnTitle"));					
				}
				
				infoListModel.setInfoLinkURL(getURLPrefix(request)+infoLinkURL);
				infoListModel.setMoreLinkURL(getURLPrefix(request)+moreLinkURL);
				
				JSONArray jsonArray = jsonObject.getJSONArray("infomations");
				if (jsonArray != null && jsonArray.length() > 0){
					for (int i=0;i < jsonArray.length();i++){
						JSONObject tempJsonObject = (JSONObject)jsonArray.get(i);
						DataRow row = new DataRow();			
						infoListModel.getRecordList().add(row);
						row.put("id",tempJsonObject.get("id"));
						row.put("title",tempJsonObject.get("title"));
						row.put("shortTitle",tempJsonObject.get("shortTitle"));
						row.put("readCount",tempJsonObject.get("readCount"));
						row.put("publishTime",tempJsonObject.get("publishTime"));
					}
				}
				StringWriter writer = new StringWriter();
				String tempateURL = urlPrefix+"/resource?PortletTemptProvider&actionType=retrieveContent&contentId="+templateId;
				String template = this.retrieveData(preferences, tempateURL);
				generate(infoListModel, template, writer);
				String html = writer.toString();
				request.setAttribute("content", html);
			} catch (Exception e) {
				request.setAttribute("content", "");
			}
		}
		super.doView(request, response);
	}
	
	private String getURLPrefix(RenderRequest request){
		return request.getContextPath()+"/"+ "request/";
	}
	
	private String retrieveData(PortletPreferences preferences,String dataURL) throws Exception{
		String ajaxData = "";
		String cacheMinutes = (String)preferences.getValue("cacheMinutes",defaultCacheMinutes);
		String isCache = preferences.getValue("isCache", defaultIsCache);
		ajaxData = PortletCacheManager.getOnly().getCachedData(isCache, dataURL, cacheMinutes);
		return ajaxData;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void generate(InfomationsModel infoListModel,String template,StringWriter writer) {
		String encoding = "utf-8";
		try {
        	Configuration cfg = new Configuration();
        	cfg.setTemplateLoader(new StringTemplateLoader(template));  
        	cfg.setEncoding(Locale.getDefault(), encoding);
            cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
        	Template temp = cfg.getTemplate("");
        	temp.setEncoding(encoding);
            Map root = new HashMap();
            root.put("model",infoListModel);
            temp.process(root, writer);
            writer.flush();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	@RenderMode(name = "edit")
	public void edit(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
		String templateId = preferences.getValue("templateId", null);
		String columnId = preferences.getValue("columnId", null);
		String unShowColumnIds = preferences.getValue("unShowColumnIds", null);
		String maxCount = preferences.getValue("maxCount", "10");
		
		String sortPolicy = preferences.getValue("sortPolicy",InfomationManage.SortPolicy.Top8PublishTime);
		String infoLinkURL = preferences.getValue("infoLinkURL", null);
		String moreLinkURL = preferences.getValue("moreLinkURL", null);
		
		String isCache = preferences.getValue("isCache", defaultIsCache);
		String cacheMinutes = preferences.getValue("cacheMinutes", defaultCacheMinutes);
		
		request.setAttribute("templateId", templateId);
		request.setAttribute("columnId", columnId);
		request.setAttribute("unShowColumnIds", unShowColumnIds);
		
		request.setAttribute("maxCount", maxCount);
		request.setAttribute("sortPolicy", sortPolicy);
		request.setAttribute("infoLinkURL", infoLinkURL);
		request.setAttribute("moreLinkURL", moreLinkURL);
		
		request.setAttribute("isCache", isCache);
		request.setAttribute("cacheMinutes", cacheMinutes);
		
		super.doEdit(request, response);
	}

	@ProcessAction(name = "saveConfig")
	public void saveConfig(ActionRequest request, ActionResponse response)
			throws ReadOnlyException, PortletModeException, ValidatorException,
			IOException, PreferenceException {
		String templateId = request.getParameter("templateId");
		String columnId = request.getParameter("columnId");
		String unShowColumnIds = request.getParameter("unShowColumnIds");
		String maxCount = request.getParameter("maxCount");
		String sortPolicy = request.getParameter("sortPolicy");
		String infoLinkURL = request.getParameter("infoLinkURL");
		String moreLinkURL = request.getParameter("moreLinkURL");
		
		String isCache = request.getParameter("isCache");
		String cacheMinutes = request.getParameter("cacheMinutes");
		
		PreferencesWrapper preferWapper = new PreferencesWrapper();		
		preferWapper.setValue("templateId", templateId);
		preferWapper.setValue("columnId", columnId);
		preferWapper.setValue("unShowColumnIds", unShowColumnIds);
		
		preferWapper.setValue("maxCount", maxCount);
		preferWapper.setValue("sortPolicy", sortPolicy);
		preferWapper.setValue("infoLinkURL", infoLinkURL);
		preferWapper.setValue("moreLinkURL", moreLinkURL);
		
		preferWapper.setValue("isCache", isCache);
		preferWapper.setValue("cacheMinutes", cacheMinutes);
		
		PreferencesHelper.savePublicPreferences(request, preferWapper.getPreferences());	
		response.setPortletMode(PortletMode.VIEW);
	}
}
